package com.pansoft.openplanet.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.pansoft.library.utils.OkHttpUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.BtcNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.TCLoadingDataView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.bitcoinj.core.Coin;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BottomWalletChooseDialogFragment extends BottomSheetDialogFragment {

    private static final String TAG = "BottomWalletChooseDialo";
    private Context mContext;
    private List<WalletBean> list = new ArrayList<>();
    private WalletAdapter walletAdapter;
    private int mode;
    private boolean hideBalace = false;

    private OnWalletSelectChangedListener onWalletSelectChangedListener;

    public BottomWalletChooseDialogFragment() {
    }


    @Override
    public void onStart() {
        super.onStart();
//        getDialog().getWindow()
//                .setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//        getDialog().getWindow().setGravity(Gravity.BOTTOM);
//        getDialog().setCanceledOnTouchOutside(true);
//        getDialog().setCancelable(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_wallet_choose_popup, container, false);
        initView(rootView);
        return rootView;
    }

    private void initView(View contentView) {

        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        walletAdapter = new WalletAdapter(mContext, R.layout.open_planet_item_wallet, list);
        recyclerView.setAdapter(walletAdapter);
        if (mode == IPAssetsConstant.CHAIN_ID_BTC) {
            getBtcBalaces();
        } else {
            initServerData();
        }
    }

    private void initServerData() {
        final HashMap<String, String> map = new HashMap<>();

        map.put("mainAccountAddress", new AccountDao(getActivity()).getMainAccount().getAddress());

        TCRequestUtil.getCommonRequest(TAG, "account/getAllWallet", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {

                        Log.i(TAG, response + "");
                        try {
                            JSONObject jsonObject = JSONObject.fromObject(response);
                            if (jsonObject.optString("result", "").equals("success")) {
                                JSONArray jsonArray = jsonObject.optJSONArray("ChildrenWallet");
                                if (jsonArray != null) {
                                    for (int i = 0; i < jsonArray.size(); i++) {
                                        for (int j = 0; j < list.size(); j++) {
                                            if (list.get(j).getAddress()
                                                    .equalsIgnoreCase(jsonArray.getJSONObject(i).optString("accountAddress", ""))) {
                                                String balance = jsonArray.getJSONObject(i).optString("balance", "0");
                                                if (!"0".equals(balance)) {
                                                    balance = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                                                }
                                                list.get(j).setBalance(balance);
                                            }
                                        }
                                    }
                                    walletAdapter.notifyDataSetChanged();
                                }

                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFail(String error) {


                    }
                });
    }

    /**
     * 获取btc余额
     */
    private void getBtcBalaces() {
        StringBuilder stringBuilder = new StringBuilder();
        if (list.size() <= 0)
            return;
        for (WalletBean walletBean : list) {
            stringBuilder.append(walletBean.getAddress()).append("_");
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        String addresses = stringBuilder.toString();

        OkHttpUtils.netRequest("get",
                BtcNetParamUtil.URL_BTC_GET_BALANCE + addresses + "&type=" + BtcNetParamUtil.NET_TYPE,
                null, null, new OkHttpUtils.DownloadListener() {
                    @Override
                    public void onSuccess(byte[] bytes) {
                        TCLoadingDataView.dismiss();
                        try {
                            org.json.JSONObject jsonObject = new org.json.JSONObject(new String(bytes));
                            if (jsonObject.optString("result").equals("success")) {
                                org.json.JSONArray jsonArray = jsonObject.optJSONArray("data");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    org.json.JSONObject dataObject = jsonArray.optJSONObject(i);
                                    for (WalletBean walletBean : list) {
                                        if (walletBean.getAddress().equals(dataObject.optString("address"))) {
                                            String balance = Coin.valueOf(Long.valueOf(dataObject.optString("finalBalance"))).toFriendlyString();
                                            if (balance == null) balance = "0";
                                            balance = balance.replace(" BTC", "");
                                            walletBean.setBalance(balance);
                                        }
                                    }
                                }
                                walletAdapter.notifyDataSetChanged();
                            } else {

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
//                            ToastUtils.showShort("请求出错，请重试");
                        }

                    }

                    @Override
                    public void onFailure(String s) {
                        TCLoadingDataView.dismiss();
                        Coin balance = Coin.valueOf(0);
                        EventBus.getDefault().post(balance);
//                        ToastUtils.showShort("请求出错，请重试");
                    }
                });
    }

    public void setData(Context context, List<WalletBean> list, int mode) {
        this.mContext = context;
        this.list = list;
        this.mode = mode;
    }

    public void hideBalace(boolean hide) {
        this.hideBalace = hide;
    }

    public class WalletAdapter extends CommonAdapter<WalletBean> {

        public WalletAdapter(Context context, int layoutId, List<WalletBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(com.efounder.recycleviewhelper.base.ViewHolder holder, final WalletBean walletBean, int position) {

            ImageView mIvWallet;
            TextView mTvAssetName;
            TextView mTvBalance;
            ImageView mIvCheck;

            mIvWallet = (ImageView) holder.getView(R.id.iv_wallet);
            mTvAssetName = (TextView) holder.getView(R.id.tv_asset_name);
            mTvBalance = (TextView) holder.getView(R.id.tv_balance);
            mIvCheck = (ImageView) holder.getView(R.id.iv_check);

            if (mode == IPAssetsConstant.CHAIN_ID_BTC) {
                if (walletBean.getAvatar() == null || walletBean.getAvatar().equals("")) {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, mIvWallet,
                            R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                } else {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, mIvWallet,
                            walletBean.getAvatar(), R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                }
            } else {
                if (walletBean.getAvatar() == null || walletBean.getAvatar().equals("")) {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, mIvWallet,
                            R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                } else {
                    LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, mIvWallet,
                            walletBean.getAvatar(), R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                }
            }

            mTvAssetName.setText(walletBean.getAccountName());
            String unit;
            switch (mode) {
                case IPAssetsConstant.CHAIN_ID_BTC:
                    unit = "BTC";
                    break;
                case IPAssetsConstant.CHAIN_ID_ETH:
                    unit = "ETH";
                    break;
                case IPAssetsConstant.CHAIN_ID_ETE:
                    unit = "ETE";
                    break;
                case IPAssetsConstant.CHAIN_ID_EOS:
                case IPAssetsConstant.CHAIN_ID_EOSTEST:
                    unit = "EOS";
                    break;
                default:
                    unit = "ETH";
                    break;
            }
            if (walletBean.isSelected()) {
                mIvCheck.setVisibility(View.VISIBLE);
            } else {
                mIvCheck.setVisibility(View.GONE);
            }
            if (hideBalace) {
                mIvCheck.setVisibility(View.GONE);
                mTvBalance.setText(walletBean.getAddress());
            } else {
                mTvBalance.setText("金额：" + walletBean.getBalance() + " " + unit);
            }


            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onWalletSelectChangedListener != null) {
                        for (WalletBean walletBean1 : list) {
                            walletBean1.setSelected(false);
                        }
                        walletBean.setSelected(true);
                        walletAdapter.notifyDataSetChanged();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                onWalletSelectChangedListener.onWalletChanged(walletBean);
                                dismiss();
                                onWalletSelectChangedListener = null;
                            }
                        }, 500);

                    }
                }
            });
        }
    }

    public interface OnWalletSelectChangedListener {
        void onWalletChanged(WalletBean walletBean);
    }

    public void setOnWalletSelectChangedListener(OnWalletSelectChangedListener onWalletSelectChangedListener) {
        this.onWalletSelectChangedListener = onWalletSelectChangedListener;
    }

}
